package cn.goktech.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.aop.support.annotation.AnnotationMethodMatcher;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller

public class FileUpload {

    @RequestMapping("/fileupload")
    public String fileUpload(@RequestParam("file") List<MultipartFile> files, HttpServletRequest request) throws IOException {

        //1、获取file文件对象

        //2、获取保存的文件路径
        String path = request.getSession().getServletContext().getRealPath("/static/images");
        System.out.println(path);
        File upFile = new File(path);
        if (!upFile.exists()) {
            upFile.mkdirs();
        }
        for (MultipartFile file : files) {
            //3、重命名
            //获取文件原始名
            String filename = file.getOriginalFilename();
            System.out.println("文件原始名：" + filename);
            //获取后缀
            String sub = filename.substring(filename.lastIndexOf("."));
            //校验文件类型
            //重命名之后的文件名
            String newFilename = UUID.randomUUID().toString() + sub;
            System.out.println("重命名后的=" + newFilename);
            //保存到文件：.../static/images/重命名后的文件名
            File newFile = new File(path + File.separator + newFilename);
            file.transferTo(newFile);
        }
        //4、保存
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("message", "文件上传成功");
        return "success";
    }

    @RequestMapping("/getImageList")
    public ModelAndView getImagesList(HttpServletRequest request, ModelAndView mv) {
        String path = request.getSession().getServletContext().getRealPath("/static/images");
        File file = new File(path);
        //获取文件下的所有文件
        File[] files = file.listFiles();
        mv.addObject("files", files);
        mv.addObject("realPath", path);
        mv.setViewName("download");
        return mv;
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(String filename,HttpServletRequest request) throws IOException {
        String path = request.getSession().getServletContext().getRealPath("/static/images");
        File file = new File(path+File.separator + filename);
        //等价以下代码通过流读取数据到字节数组中
         //byte[] fileBytes = FileUtils.readFileToByteArray( new File(path+File.separator + filename) );
        //获取文件的输入流
        FileInputStream fis = new FileInputStream(file);
        //将文件的可读取的最大字节数用来创建数组对象
        byte[] bytes = new byte[fis.available()];
        //利用字节流读取文件存放到字节数组中
        fis.read(bytes);
        //（2）、 创建请求头，设置请求头信息
        HttpHeaders httpHeaders = new HttpHeaders();
        //设置响应方式，以二进制流传输
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //告诉浏览器执行下载的操作，“attachment”告诉了浏览器进行下载,下载的文件文件名为 fileName
        httpHeaders.setContentDispositionFormData("attachment",filename);
        return  new ResponseEntity<byte[]>(bytes, httpHeaders, HttpStatus.CREATED);
    }
}
